package com.sd.repay.controller;

import com.sd.repay.common.CommonResult;
import com.sd.repay.common.Constants;
import com.sd.repay.pojo.ExtractionOrder;
import com.sd.repay.pojo.MerchantUser;
import com.sd.repay.pojo.SmsInfo;
import com.sd.repay.service.*;
import com.sd.repay.utils.DateUtil;
import com.sd.repay.utils.JsonUtil;
import com.sd.repay.utils.StringUtil;
import com.sd.repay.utils.WebUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by sd on 2018/08/21
 * 提现控制类
 */
@Controller
@RequestMapping(value = "/postalCash")
public class PostalcashController {

    private static final Logger log = LoggerFactory.getLogger(PostalcashController.class);

    @Autowired
    private MerchantService merchantService;
    @Autowired
    private MerFeeService merFeeService;
    @Autowired
    private BalanceOperService balanceOperService;
    @Autowired
    private CardManageService cardManageService;
    @Autowired
    private AgentService agentService;
    @Autowired
    private CashService cashService;
    @Autowired
    private SmsService smsService;


    /**
     * 提现
     *
     * @return
     */
    @RequestMapping(value = "/cash", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8")
    @ResponseBody
    public CommonResult cash(HttpServletRequest request, @RequestParam Map<String, String> params) {
        log.info("提现接受参数：[{}]", JsonUtil.objectToJson(params));
        String oemType = request.getParameter("oemType");
        String osType = request.getParameter("osType");
        String merType = request.getParameter("merType");
        String merNo = request.getParameter("merNo");
        String amount = request.getParameter("amount");

        oemType = StringUtils.isBlank(oemType) ? Constants.DEFAULT_OEM_TYPE : oemType;
        try {
            //如果是客户端，必须是登录状态
            if ("android".equalsIgnoreCase(osType) || "iOS".equalsIgnoreCase(osType)) {
                MerchantUser currUser = WebUtil.getCurrMerchantUser();
                if (null == currUser) {
                    return CommonResult.build(403, "请先登录");
                }
                merType = Constants.MER_TYPE_MERCHANT;
                merNo = currUser.getMerchantNo();

                String smsCode = request.getParameter("smsCode");
                if(StringUtils.isBlank(smsCode)){
                    return CommonResult.build(403, "验证码不能为空");
                }
                //验证短信验证码
                SmsInfo smsInfo = new SmsInfo();
                smsInfo.setMobiles(currUser.getMobileNo());
                smsInfo.setSms_business(Constants.SMS_BUSINESS_MERCHANT_CASH);
                smsInfo.setVali_code(smsCode);

                smsService.checkValidateCode(smsInfo);
                String smsStatus = smsInfo.getVali_status();
                if (!Constants.SMS_VALI_STATUS_PASS.equals(smsStatus)) {
                    return CommonResult.build(403, "短信验证码错误");
                }
            }
            if (StringUtil.isBlank(merType, merNo, amount)) {
                return CommonResult.build(403, "必要参数不能为空");
            }
            BigDecimal amountBig = BigDecimal.ZERO;
            try {
                amountBig = new BigDecimal(amount);
            } catch (Exception e) {
                return CommonResult.build(403, "提现金额不合法");
            }
            if (amountBig.compareTo(BigDecimal.ZERO) < 0) {
                return CommonResult.build(403, "提现金额必须大于0");
            }
            //判断提现开关
            String cashStatus = WebUtil.getSysValue("REPAY_CASH_STATUS");
            if (!"1".equals(cashStatus)) {
                return CommonResult.build(403, "当前提现功能关闭,不允许提现");
            }
            //系统允许提现时间
            Date now = new Date();
            int currHour = Integer.parseInt(DateUtil.format(now, "HH"));
            try {
                String cashTime = WebUtil.getSysValue("REPAY_CASH_TIME");
                String[] cashTimeArray = cashTime.split("-");
                int allowBeginHour = Integer.parseInt(cashTimeArray[0]);
                int allowEndHour = Integer.parseInt(cashTimeArray[1]);
                if (currHour < allowBeginHour || currHour > allowEndHour) {
                    return CommonResult.build(403, "不在系统允许提现时间" + allowBeginHour + "-" + allowEndHour + "内");
                }
            } catch (Exception e) {
                return CommonResult.build(403, "系统允许提现时间配置异常");
            }

            //获取用户信息
            Map<String, Object> merInfo = new HashMap<>();
            if (Constants.MER_TYPE_MERCHANT.equals(merType)) {
                merInfo = merchantService.getMerInfoByMerNo(merNo);
            } else if (Constants.MER_TYPE_AGENT.equals(merType)) {
                merInfo = agentService.getAgentInfoByAgentNo(merNo);
            } else {
                return CommonResult.build(403, "用户类型不合法");
            }
            log.info("提现用户类型[{}]用户编号[{}]对应的用户信息[{}]", new Object[]{merType, merNo, JsonUtil.objectToJson(merInfo)});
            if (null == merInfo || merInfo.isEmpty()) {
                return CommonResult.build(403, "用户信息不存在");
            }
            String idCardNo = StringUtil.filterNull(merInfo.get("id_card_no"));
            //获取用户当前结算卡
            Map<String, Object> settleCardInfo = cardManageService.getSettleCardInfoByIdCard(idCardNo);
            log.info("提现用户类型[{}]用户编号[{}]对应的结算卡信息[{}]", new Object[]{merType, merNo, JsonUtil.objectToJson(settleCardInfo)});
            if (null == settleCardInfo || settleCardInfo.isEmpty()) {
                return CommonResult.build(403, "当前用户还未绑定结算卡");
            }
            String cardNo = StringUtil.filterNull(settleCardInfo.get("card_no"));
            String mobile = StringUtil.filterNull(settleCardInfo.get("mobile_no"));
            String settleBankNo = StringUtil.filterNull(settleCardInfo.get("bank_no"));
            String accountName = StringUtil.filterNull(settleCardInfo.get("account_name"));
            String accountNo = StringUtil.filterNull(settleCardInfo.get("account_no"));
            String bankName = StringUtil.filterNull(settleCardInfo.get("bank_name"));

            //获取提现费率信息
            Map<String, Object> merFeeInfo = merFeeService.getMerFeeByMerNoAndOemType(merType, merNo, oemType);
            log.info("提现用户类型[{}]用户编号[{}]对应的提现费率信息[{}]", new Object[]{merType, merNo, JsonUtil.objectToJson(merFeeInfo)});
            if (null == merFeeInfo || merFeeInfo.isEmpty()) {
                return CommonResult.build(403, "用户提现费率信息为空");
            }
            String cashFeeRate = StringUtil.filterNull(merFeeInfo.get("withdraw_fee_rate"));
            String casgSingleFee = StringUtil.filterNull(merFeeInfo.get("withdraw_single_fee"));
            cashFeeRate = StringUtils.isBlank(cashFeeRate) ? "0.00" : cashFeeRate;
            casgSingleFee = StringUtils.isBlank(casgSingleFee) ? "0" : casgSingleFee;

            BigDecimal cashFeeRateBig = BigDecimal.ZERO;
            BigDecimal casgSingleFeeBig = BigDecimal.ZERO;
            BigDecimal totalFeeBig = BigDecimal.ZERO;
            try {
                cashFeeRateBig = new BigDecimal(cashFeeRate);
                casgSingleFeeBig = new BigDecimal(casgSingleFee);
                totalFeeBig = amountBig.multiply(cashFeeRateBig).add(casgSingleFeeBig);
                if (amountBig.compareTo(totalFeeBig) < 0) {
                    return CommonResult.build(403, "提现金额小于提现手续费" + totalFeeBig.toPlainString());
                }
            } catch (Exception e) {
                return CommonResult.build(403, "提现费率不合法");
            }

            ExtractionOrder extOrder = new ExtractionOrder();
            extOrder.setOrderNo(WebUtil.nextUniqueSeqNo("t_extraction_order", "EXTO", 25));
            extOrder.setMerType(merType);
            extOrder.setMerNo(merNo);
            extOrder.setAcqCode(Constants.CASH_ACQ_CODE_YUN);
            extOrder.setCardNo(cardNo);
            extOrder.setAccountNo(accountNo);
            extOrder.setAccountName(accountName);
            extOrder.setMobileNo(mobile);
            extOrder.setIdCardNo(idCardNo);
            extOrder.setAmount(amountBig);
            extOrder.setFee(totalFeeBig);
            extOrder.setBak1(settleBankNo);
            extOrder.setBak2(bankName);

            log.info("提现用户类型[{}]用户编号[{}]发起提现参数[{}]", new Object[]{merType, merNo, JsonUtil.objectToJson(extOrder)});
            return cashService.postalCash(extOrder);

        } catch (Exception e) {
            e.printStackTrace();
            log.info("提现用户类型[{}]提现用户编号[{}]提现异常[{}]", new Object[]{merType, merNo, e});
            return CommonResult.build(403, "提现失败，请稍候再试");
        }
    }
}
